using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;

namespace GenericExampleParticleSystem
{    
    public class SkyBox : DrawableGameComponent
    {
        private Model skyboxMesh;
        public Vector3 myPosition;
        public Quaternion myRotation;
        public Vector3 myScale;

        public TextureCube environ;

        Effect shader;

        string modelAsset;
        string shaderAsset;
        string textureAsset;

        ContentManager content;

        public SkyBox(Game game, string modelAsset, string shaderAsset, string textureAsset)
            : base(game)
        {
            content = new ContentManager(game.Services);

            this.modelAsset = modelAsset;
            this.shaderAsset = shaderAsset;
            this.textureAsset = textureAsset;

            myPosition = new Vector3(0, 0, 0);
            myRotation = new Quaternion(0, 0, 0, 1);
            myScale = new Vector3(55, 55, 55);
        }
         
        protected override void UnloadContent()
        {
            content.Unload();
            base.UnloadContent();
        }

        protected override void LoadContent()
        {

            skyboxMesh = content.Load<Model>(modelAsset);
            shader = content.Load<Effect>(shaderAsset);
            environ = content.Load<TextureCube>(textureAsset);
            base.LoadContent();
        }

        public override void Draw(GameTime gameTime)
        {
            Matrix World = Matrix.CreateScale(myScale) *
                            Matrix.CreateFromQuaternion(myRotation) *
                            Matrix.CreateTranslation(Camera.myPosition);


            try
            {
                shader.Parameters["World"].SetValue(World);
                shader.Parameters["View"].SetValue(Camera.myView);
                shader.Parameters["Projection"].SetValue(Camera.myProjection);
                shader.Parameters["surfaceTexture"].SetValue(environ);

                shader.Parameters["EyePosition"].SetValue(Camera.myPosition);


                for (int pass = 0; pass < shader.CurrentTechnique.Passes.Count; pass++)
                {
                    for (int msh = 0; msh < skyboxMesh.Meshes.Count; msh++)
                    {
                        ModelMesh mesh = skyboxMesh.Meshes[msh];
                        for (int prt = 0; prt < mesh.MeshParts.Count; prt++)
                            mesh.MeshParts[prt].Effect = shader;
                        mesh.Draw();
                    }
                }
            }
            catch (AccessViolationException)
            {
                MessageBox.Show("error!");
            }

            base.Draw(gameTime);
        }
    }
}
